package com.ruoyi.common.utils;

import java.lang.management.ManagementFactory;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.IntStream;

import cn.hutool.core.date.DateUtil;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.objenesis.instantiator.sun.MagicInstantiator;

/**
 * 时间工具类
 * 
 * @author ruoyi
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils
{
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", 
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 获取当前Date型日期
     * 
     * @return Date() 当前日期
     */
    public static Date getNowDate()
    {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     * 
     * @return String
     */
    public static String getDate()
    {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime()
    {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow()
    {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format)
    {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date)
    {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date)
    {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts)
    {
        try
        {
            return new SimpleDateFormat(format).parse(ts);
        }
        catch (ParseException e)
        {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str)
    {
        if (str == null)
        {
            return null;
        }
        try
        {
            return parseDate(str.toString(), parsePatterns);
        }
        catch (ParseException e)
        {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate()
    {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算相差天数
     */
    public static int differentDaysByMillisecond(Date date1, Date date2)
    {
        return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24)));
    }

    /**
     * 计算时间差
     *
     * @param endDate 最后时间
     * @param startTime 开始时间
     * @return 时间差（天/小时/分钟）
     */
    public static String timeDistance(Date endDate, Date startTime)
    {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - startTime.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * 增加 LocalDateTime ==> Date
     */
    public static Date toDate(LocalDateTime temporalAccessor)
    {
        ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 增加 LocalDate ==> Date
     */
    public static Date toDate(LocalDate temporalAccessor)
    {
        LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
        ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /***
     * 获取某天每小时数据集合
     * make by xumh on 2024-12-07
     * @param day 2024-01-01
     * @return 2024-01-01 00 ..... 2024-01-01 23
     */
    public static List<String> assembleHour(String day){
        List<String> hourList = new ArrayList<>();
        for(int i=0;i<24;i++){
            if (i<10){hourList.add(day+" 0"+i);}else{hourList.add(day+" "+i);}
        }
        return hourList;
    }

    /**
     * 包含今天 过去n天的日期数据集合
     * @param num 是几就是过去几天
     * @return
     */
    public static List<String> assemblePastday(int num){
        List<String> dayList = new ArrayList<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        for (int i = 0; i < num; i++) {
            dayList.add(simpleDateFormat.format(calendar.getTime()));
            calendar.add(Calendar.DAY_OF_MONTH, -1); // 减去一天
        }
        return dayList;
    }

    /***
     * 获取某年某月里的日期数据集合
     * make by xumh on 2024-12-07
     * @param yearMonth 2024-01
     * @return 2024-01-01 ..... 2024-01-31
     */
    public static List<String> assembleDay(String yearMonth) {
        String begin = yearMonth+"-01";
        String end = DateUtil.format(DateUtil.endOfMonth(DateUtil.parse(begin,"yyyy-MM-dd")),"yyyy-MM-dd");
        List<String> list = new ArrayList<String>();
        Calendar cld = Calendar.getInstance();
        for (int i = 0; i < 62; i++) {
            cld.setTime(DateUtil.parse(begin, "yyyy-MM-dd"));
            cld.add(Calendar.DATE, +i);
            String month = DateUtil.format(cld.getTime(), "yyyy-MM-dd");
            list.add(month);
            if (month.equals(end.substring(0, 10))) {
                break;
            }
        }
        return list;
    }

    /***
     * 获取某年每月的月份数据集合
     * make by xumh on 2024-12-07
     * @param year 2024
     * @return 2024-01 ..... 2024-12
     */
    public static List<String> assembleMonth(int year){
        List<String> monthList = new ArrayList<>();
        for(int i=1;i<=12;i++){
            if (i<10){monthList.add(year+"-0"+i);}else{monthList.add(year+"-"+i);}
        }
        return monthList;
    }

    /***
     *
     * 计算时间加分钟数的方法
     */
    public static String dateStrAddNumber(String fromTime,String dateType, int overTime) {
        int dateTypeInt = 1;
        if (dateType.equals("SECOND")){ //秒
            dateTypeInt = Calendar.SECOND;
        }else if(dateType.equals("MINUTE")){ //分
            dateTypeInt = Calendar.MINUTE;
        }else if(dateType.equals("HOUR")){ //时
            dateTypeInt = Calendar.HOUR;
        }else if(dateType.equals("DAY")){ //日
            dateTypeInt = Calendar.DATE;
        }else if(dateType.equals("MONTH")){ //月
            dateTypeInt = Calendar.MONTH;
        }else if(dateType.equals("YEAR")){ //年
            dateTypeInt = Calendar.YEAR;
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = dateFormat.parse(fromTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(dateTypeInt, overTime);//这里是分钟，如果需要，可以更换为day,moth
        Date date1 = calendar.getTime();
        Timestamp overQTimeKey = new Timestamp(calendar.getTime().getTime());
        SimpleDateFormat overQTimeDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return overQTimeDateFormat.format(overQTimeKey);
    }

    /***
     * 获取 开始结束时间
     * 本/去年
     * 本/上月
     * 本/上周
     * 昨/今日 的开始和结束时间 String类型
     * @return map 时间字符串
     */
    public static Map<String,String> getBegEndDates(){
        Map<String,String> item = new HashMap<>();
        //本年开始 结束时间
        String beginThisYear=  DateUtil.year(new Date())+"-01-01 00:00:00";
        String endThisYear =  DateUtil.year(new Date())+"-12-31 23:59:59";
        item.put("beginThisYear",beginThisYear);
        item.put("endThisYear",endThisYear);

        //上个月开始 结束时间
        LocalDate now = LocalDate.now().minusMonths(1);//月份-1
        LocalDate firstDay = now.with(TemporalAdjusters.firstDayOfMonth());// 获取当前月的第一天
        LocalDate lastDay = now.with(TemporalAdjusters.lastDayOfMonth()); // 获取当前月的最后一天
        Date startTime = Date.from(firstDay.atStartOfDay(ZoneId.systemDefault()).toInstant());//上个月第一天
        Date endTime = Date.from(lastDay.atStartOfDay(ZoneId.systemDefault()).toInstant());//上个月最后一天
        String beginLastMonth = DateUtil.format(startTime,"yyyy-MM-dd")+" 00:00:00";
        String endLastMonth = DateUtil.format(endTime,"yyyy-MM-dd")+" 23:59:59";
        item.put("beginLastMonth",beginLastMonth);
        item.put("endLastMonth",endLastMonth);

        //本月开始 结束时间
        String beginThisMonth =  DateUtil.format(DateUtil.beginOfMonth(new Date()),"yyyy-MM-dd")+" 00:00:00";
        String endThisMonth =  DateUtil.format(DateUtil.endOfMonth(new Date()),"yyyy-MM-dd")+" 23:59:59";
        item.put("beginThisMonth",beginThisMonth);
        item.put("endThisMonth",endThisMonth);

        //本周开始 结束时间
        String beginThisWeek =  DateUtil.format(DateUtil.beginOfWeek(new Date()),"yyyy-MM-dd")+" 00:00:00";
        String endThisWeek =  DateUtil.format(DateUtil.endOfWeek(new Date()),"yyyy-MM-dd")+" 23:59:59";
        item.put("beginThisWeek",beginThisWeek);
        item.put("endThisWeek",endThisWeek);

        //上周开始 结束时间
        String beginLastWeek = LocalDate.now().minusWeeks(1).with(TemporalAdjusters.previous(DayOfWeek.SUNDAY)).plusDays(1L)+" 00:00:00";
        String endLastWeek = LocalDate.now().minusWeeks(1).with(TemporalAdjusters.next(DayOfWeek.MONDAY)).minusDays(1L)+" 23:59:59";
        item.put("beginLastWeek",beginLastWeek);
        item.put("endLastWeek",endLastWeek);

        //昨天开始 结束时间
        String beginYesterday =  DateUtil.format(DateUtil.yesterday(),"yyyy-MM-dd")+" 00:00:00";
        String endYesterday =  DateUtil.format(DateUtil.yesterday(),"yyyy-MM-dd")+" 23:59:59";
        item.put("beginYesterday",beginYesterday);
        item.put("endYesterday",endYesterday);

        //今天开始 结束时间
        String beginNowDay =  DateUtil.format(new Date(),"yyyy-MM-dd")+" 00:00:00";
        String endNowDay =  DateUtil.format(new Date(),"yyyy-MM-dd")+" 23:59:59";
        item.put("beginNowDay",beginNowDay);
        item.put("endNowDay",endNowDay);

        return item;
    }

    /***
     * 获取上周的7天的日期
     * @return
     */
    public static List<LocalDate> getLastWeekDay() {
        LocalDate lastMonday = LocalDate.now().minusWeeks(1).with(TemporalAdjusters.previous(DayOfWeek.SUNDAY)).plusDays(1L);
        List<LocalDate> lastWeekDates = new ArrayList<>();

        // 获取上周的7天日期
        IntStream.range(0, 7)
                .mapToObj(days -> lastMonday.plusDays(days))
                .forEach(lastWeekDates::add);
        return lastWeekDates;
    }

    /***
     * 获取本周的7天的日期
     * @return Date数组
     */
    public static Date[] getNowWeekDay() {
        Calendar calendar = Calendar.getInstance();
        while (calendar.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
            calendar.add(Calendar.DAY_OF_WEEK, -1);
        }
        Date[] dates = new Date[7];  // new Date[7] 星期日
        for (int i = 0; i < 7; i++) {  // i < 7 星期日
            dates[i] = calendar.getTime();
            calendar.add(Calendar.DATE, 1);
        }
        return dates;
    }

    /***
     * 获取上个月的天数
     * @return
     */
    public static int getLastMonthDays(){
        // 获取当前年月
        YearMonth currentYearMonth = YearMonth.now();
        // 获取上个月的年月
        YearMonth previousYearMonth = currentYearMonth.minusMonths(1);
        // 获取上个月的天数
        int daysInPreviousMonth = previousYearMonth.lengthOfMonth();
        return daysInPreviousMonth;
    }
    /***
     * 获取本月的天数
     * @return
     */
    public static int getNowMonthDays(){
        // 获取当前年月
        YearMonth currentYearMonth = YearMonth.now();
        int daysInPreviousMonth = currentYearMonth.lengthOfMonth();
        return daysInPreviousMonth;
    }

    /**
     * 以文字描述返回传入时间与当前时间的间隔
     * @param date
     * @return
     */
    public static String pastime2display(Date date) {
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yy/MM/dd hh:mm");

        try {
            long l = now.getTime() - date.getTime();
            long day = l / 86400000L;
            long hour = l / 3600000L - day * 24L;
            long min = l / 60000L - day * 24L * 60L - hour * 60L;
            long s = l / 1000L - day * 24L * 60L * 60L - hour * 60L * 60L - min * 60L;
            if (day > 60L) {
                return sdf.format(date);
            }

            if (day > 0L) {
                if (day < 30L) {
                    return day + "天前";
                }

                return "一个月前";
            }

            if (hour > 0L) {
                return hour + "小时前";
            }

            if (min > 0L) {
                return min + "分钟前";
            }

            if (s > 0L) {
                return "刚刚";
            }
        } catch (Exception var13) {
            var13.printStackTrace();
        }

        return "";
    }

    public static void main(String[] args) {
        System.out.println(pastime2display(DateUtil.parse( "2024-12-12 16:08:09")));
    }
}
